import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home'
import index from '../views/index'

Vue.use(VueRouter)

const routes = [
  {
    path:'/',
    name:'Home',
    component:Home,
    redirect:'index',
    children:[
      {
        path:'index',
        name:'index',
        component:index,
        // meta:{guard:true},
      },
      {
        path:'ShopDetail/:id',
        name:'ShopDetail',
        component:() => import('@/views/ShopDetail')
      },
      {
        path:'ShopShow/:id',
        name:'ShopShow',
        component:() => import ('../views/ShopShow'),
      },
    ]
  },
  {
    path:'/order',
    name:'order',
    component:() => import('@/views/order'),
    redirect:'order/orderConfirm',
    children:[
      {
        path:'orderConfirm',
        name:'orderConfirm',
        component:() => import('@/views/orderConfirm'),
      },
      {
        path:'orderList',
        name:'orderList',
        component:() => import('@/views/orderList'),
      },
      {
        path:'orderPay',
        name:'orderPay',
        component:() => import('@/views/orderPay'),
      },

    ]
  },
  {
    path:'/Login',
    name:'Login',
    component:() => import ('../views/Login')
  },
  {
    path:'/Register',
    name:'Register',
    component:() => import ('../views/Register')
  },
  {
    path:'/cart',
    name:'cart',
    component:() => import('@/views/cart'),
    meta:{guard:true},
  },
  {
    path:'*',
    component:Home
  }
]

const router = new VueRouter({
  routes,
  //使得页面刷新时滚动条回到顶部
  scrollBehavior (to, from, savedPosition) {
    return { x: 0, y: 0 }
  },
})

//全局路由守卫
router.beforeEach((to,from,next) => {
  //使滚动条回到顶部
  window.scrollTo(0,0)
  if(to.meta.guard){
    if(sessionStorage.getItem('isLogin')){
      next()
    }
    else{
      //登录后重定向回原来的页面，通过to.fullPath获取目的路由路径，使用拼接的方法去传递这个地址
      next('/Login?redirect='+to.fullPath)
    }
  }
  else{
    next()
  }
})

export default router
